<?php

namespace App\Datas;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class UserDrawing
{
    public function updateUserDrawExp($userId, $drawingId, $times) {
        $userDrawData = DB::table('user_drawing')->where(["user_id" => $userId, "drawing_id" => $drawingId])->first();
        if(!$userDrawData) {
            DB::table('user_drawing')->insert(["user_id" => $userId, "drawing_id" => $drawingId, "expire_time" => $times + time()]);
        } else {
            $userDrawData = (array)$userDrawData;
            $exp = $userDrawData["expire_time"];
            $new = time();
            if ($exp < $new) {
                $exp = $new;
            }

            DB::table('user_drawing')->where(['user_id' => $userId, "drawing_id" => $drawingId])->update(["expire_time" => $exp + $times]);
        }
        return true;
    }

    //获取用户解锁的画板
    public function getUserDraw($userId)
    {
        $times = time();
        $userDrawData = DB::table('user_drawing')->select('drawing_id')->where('user_id', '=', $userId)->where('expire_time', '>=', $times)->get();
        return $userDrawData->toArray();
    }

    //用户的画板是否有效期内
    public function getUserDrawIsEffective($userId, $drawingId)
    {
        $userDrawData = DB::table('user_drawing')->where(["user_id" => $userId, "drawing_id" => $drawingId])->first();
        if (!$userDrawData) {
            return false;
        }

        $userDrawData = (array)$userDrawData;
        if ($userDrawData['expire_time'] < time()) {
            return false;
        }

        return $userDrawData['expire_time'] - time();
    }

}